package com.yk.flutter.plugin.yk_plugin

import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.os.Handler
import android.os.Looper
import android.util.Log
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result

/** YkPlugin */
class YkPlugin: FlutterPlugin, MethodCallHandler, ActivityAware {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private lateinit var channel : MethodChannel
  private var context: Context? = null
  private var activity: Activity? = null
  private val messageManager: YkPluginMessageManager = YkPluginMessageManager();

  private enum class YkPluginMessageType {
    yk_debug_test,
    yk_alert,
    yk_start_live_activity,
    yk_stop_live_activity,
    yk_reload_widget,
  }

  private inner class YkPluginMessageManager {

    private val systemMap = mutableMapOf<String, (Any?, Result) -> Unit>();

    fun registContext(type: YkPluginMessageType, callBack: (Any?, Result) -> Unit) {
      if (!systemMap.keys.contains(type.name)) {
        systemMap.put(type.name, callBack);
      }
    }

    fun executeContent(type: String, arguments: Any?, result: Result) {
      val callBack = systemMap[type];
      if (callBack != null) {
        callBack.invoke(arguments, result);
      } else {
        result.notImplemented();
      }
    }

  }

  init {
      regist();
  }

  override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    channel = MethodChannel(flutterPluginBinding.binaryMessenger, "yk_plugin")
    channel.setMethodCallHandler(this)
    context = flutterPluginBinding.applicationContext
  }

  override fun onMethodCall(call: MethodCall, result: Result) {

    messageManager.executeContent(call.method, call.arguments, result)
  }

  override fun onAttachedToActivity(binding: ActivityPluginBinding) {
    activity = binding.activity;
  }

  override fun onDetachedFromActivityForConfigChanges() {
    activity = null
  }

  override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
    onAttachedToActivity(binding);
  }

  override fun onDetachedFromActivity() {
    activity = null
  }

  override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
    channel.setMethodCallHandler(null)
  }

  private fun regist() {

    messageManager.registContext(YkPluginMessageType.yk_debug_test) { arg: Any?, result: Result ->
      if (BuildConfig.DEBUG) {
        try {
          Handler(Looper.getMainLooper()).post({
            val params = hashMapOf<String, Any?>(
              "url" to "https://www.baidu.com"
            )
            channel.invokeMethod("yk_invoked_open_url", params)
          })
        } catch (e: Exception) {
          Log.e("alert error",e.toString());
        }
        result.success("Android ${android.os.Build.VERSION.RELEASE}")
      } else {
        result.notImplemented()
      }
    }

    messageManager.registContext(YkPluginMessageType.yk_alert) { arg: Any?, result: Result ->

      try {
        val map = arg as? Map<String,Any?>;
        val title = map?.get("title") ?: "";
        val msg = map?.get("msg") ?: "";
        val comfirmBtnText = map?.get("confirmBtnText") ?: "确定";
        val cancelBtnText = map?.get("cancelBtnText") ?: "取消";
        Handler(Looper.getMainLooper()).post(kotlinx.coroutines.Runnable {
          kotlin.run {
            val dialog = AlertDialog.Builder(activity)
              .setTitle("$title")
              .setMessage("$msg")
              .setCancelable(false)
              .setPositiveButton("$comfirmBtnText", DialogInterface.OnClickListener { dialog, which ->
                dialog.dismiss();
                result.success(true);
              })
              .setNegativeButton("$cancelBtnText", DialogInterface.OnClickListener { dialog, which ->
                dialog.dismiss();
                result.success(false);
              })
              .create().show();
          }
        });
        if (BuildConfig.DEBUG) {
          Log.d("debug","alert");
        }
      } catch (e: Exception) {
        Log.e("alert error",e.toString());
        result.success(false);
      }
    }

    messageManager.registContext(YkPluginMessageType.yk_start_live_activity) { arg: Any?, result: Result ->
      if (BuildConfig.DEBUG) {
        Log.d("error", "暂不支持LiveActivity");
      }
      result.success(true);
    }

    messageManager.registContext(YkPluginMessageType.yk_stop_live_activity) { arg: Any?, result: Result ->
      if (BuildConfig.DEBUG) {
        Log.d("error", "暂不支持LiveActivity");
      }
      result.success(true);
    }

    messageManager.registContext(YkPluginMessageType.yk_reload_widget) { arg: Any?, result: Result ->
      if (BuildConfig.DEBUG) {
        Log.d("error", "暂不支持 reload widget");
      }
      result.success(true);
    }
  }
}
